import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi } from '../api/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))
  const userRole = ref(localStorage.getItem('userRole') || '')

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const isStudent = computed(() => userRole.value === 'STUDENT')
  const isMerchant = computed(() => userRole.value === 'MERCHANT')
  const isDelivery = computed(() => userRole.value === 'DELIVERY')
  const isAdmin = computed(() => userRole.value === 'ADMIN')

  // 方法
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const setUserInfo = (info) => {
    userInfo.value = info
    localStorage.setItem('userInfo', JSON.stringify(info))
  }

  const setUserRole = (role) => {
    userRole.value = role
    localStorage.setItem('userRole', role)
  }

  const login = async (loginData) => {
    try {
      const response = await loginApi(loginData)
      
      // 检查响应数据结构
      if (!response.data) {
        throw new Error('登录响应数据为空')
      }
      
      const { token, userInfo, userRole } = response.data
      
      if (!token) {
        throw new Error('登录失败：未获取到访问令牌')
      }
      
      setToken(token)
      setUserInfo(userInfo)
      // 确保userRole是字符串格式
      const roleString = userRole?.code || userRole || ''
      setUserRole(roleString)
      
      return true
    } catch (error) {
      console.error('Login failed:', error)
      throw error
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = null
    userRole.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('userRole')
  }

  const updateUserInfo = (info) => {
    setUserInfo({ ...userInfo.value, ...info })
  }

  const initFromStorage = () => {
    // 从localStorage恢复状态
    const storedToken = localStorage.getItem('token')
    const storedUserInfo = localStorage.getItem('userInfo')
    const storedUserRole = localStorage.getItem('userRole')
    
    if (storedToken) {
      token.value = storedToken
    }
    
    if (storedUserInfo) {
      try {
        userInfo.value = JSON.parse(storedUserInfo)
      } catch (e) {
        console.error('Failed to parse userInfo from localStorage:', e)
        localStorage.removeItem('userInfo')
      }
    }
    
    if (storedUserRole) {
      userRole.value = storedUserRole
    }
  }

  return {
    // 状态
    token,
    userInfo,
    userRole,
    
    // 计算属性
    isLoggedIn,
    isStudent,
    isMerchant,
    isDelivery,
    isAdmin,
    
    // 方法
    setToken,
    setUserInfo,
    setUserRole,
    login,
    logout,
    updateUserInfo,
    initFromStorage
  }
})
